import 'dart:async';
import 'dart:ffi';
import 'dart:io' as io;
import 'package:path/path.dart';
import 'package:payment/model/PayAndBal.dart';
import 'package:sqflite/sqflite.dart';


class DBHelper {
  static Database? _db;

  static final String createTableSql_payAndBal = '''
    CREATE TABLE IF NOT EXISTS pay_bal (
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, 
    consumptionObject TEXT, 
    classification TEXT,
    card INTEGER,
    total REAL,
    consumptionNum REAL,
    isPay BOOLEAN,
    imageStr TEXT, 
    updateTime INTEGER
    );
    ''';

  Future<Database?> get db async {
    if (_db != null) return _db;
    _db = await initDb();
    return _db;
  }

  initDb() async {
    String path = join(await getDatabasesPath(), "bank.db");
    var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return theDb;
  }

  void _onCreate(Database db, int version) async {
    await db.execute(createTableSql_payAndBal);
    print("建表成功");
  }

  Future<void> insertPayAndBal(PayAndBal payAndBal) async {
    var dbClient = await db;
    await dbClient!.insert(
      'pay_bal',
      payAndBal.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
    print("插入成功");
  }
  Future<List<PayAndBal>> getAllPayAndBals() async {
    final dbClient = await db;
    final List<Map<String, dynamic>> maps = await dbClient!.query('pay_bal');
    print(maps);
    return List.generate(maps.length, (i) {
      return PayAndBal(
        maps[i]['id'],
        maps[i]['consumptionObject'],
        maps[i]['classification'],
        maps[i]['card'],
        maps[i]['total'],
        maps[i]['consumptionNum'],
        maps[i]['isPay']==1? true : false,
        maps[i]['imageStr'],
        maps[i]['updateTime'],
      );
    });

  }
  Future<void> deleteTabel(String tableName) async{
    final dbClient = await db;
    await dbClient!.execute(createTableSql_payAndBal);
    print("删表"+tableName+"成功");
  }
  Future<void> deletePayAndBal(int id) async {
    final dbClient = await db;

    // Remove the Dog from the database.
    await dbClient!.delete(
      'pay_bal',
      where: 'id = ?',
      whereArgs: [id],
    );
  }
  // Future<List<PayAndBal>> getPayAndBals() async {
  //   var dbClient = await db;
  //   List<Map> list = await dbClient!.rawQuery('SELECT * FROM Employee');
  //   List<PayAndBal> payAndBals = new List();
  //   for (int i = 0; i < list.length; i++) {
  //     employees.add(new Employee(list[i]["firstname"], list[i]["lastname"], list[i]["mobileno"], list[i]["emailid"]));
  //   }
  //   print(employees.length);
  //   return employees;
  // }
}
